import pymysql

from Common.handle_config import conf

class HandleDB:
    def __init__(self):
        #建立数据库连接
        self.conn = pymysql.connect(
            host=conf.get("MYSQL","host"),
            port=conf.getint("MYSQL","port"),
            user=conf.get("MYSQL","user"),
            password=conf.get("MYSQL","password"),
            database=conf.get("MYSQL","database"),
            charset="utf8",
            cursorclass=pymysql.cursors.DictCursor  # 字典格式输出
        )
        self.cur = self.conn.cursor()

        #获取一条数据
    def select_one_data(self,sql):
        self.conn.commit()    #先同步一下数据库防止出现脏数据
        self.cur.execute(sql)
        return self.cur.fetchone()

        #获取所有数据
    def select_all_data(self,sql):
        self.conn.commit()
        self.cur.execute(sql)
        return self.cur.fetchall()

        # 获取数据条数
    def get_count(self,sql):
        self.conn.commit()
        return self.cur.execute(sql)

        #更新数据库
    def update(self,sql):
        self.cur.execute(sql)
        self.cur.commit()

        #关闭数据库
    def close(self):
        self.cur.close()
        self.conn.close()

db = HandleDB()

# if __name__ == '__main__':
#     sql = 'SELECT * FROM `user` WHERE userPhone = ""'
#     sql1 = 'SELECT * FROM `user` LIMIT 10'
#     db = HandleDB()
#     data = db.select_one_data(sql)
#     print("获取一条数据",data)
#     data = db.select_all_data(sql1)
#     print("获取全部数据",data)
#     data = db.get_count(sql)
#     print("获取条数",data)
